package com.banciyuan.bcywebview.biz.main.mineinfo.mywork;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.api.IllustApi;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.Statistics;
import de.greenrobot.daoexample.model.StatisticsItem;
import de.greenrobot.daoexample.model.User;

/**
 * Created by hy on 2016/3/21.
 */
public class StatisticsActivity extends BaseActivity implements View.OnClickListener {
    private ImageView ivStatisticsHeader;
    private TextView tvStatisticsName;
    private TextView tvStatisticsJoindate;

    private View viewWorkNum;
    private View viewLikeNum;
    private View viewCommentNum;
    private View viewBrowserNum;
    private View viewFansNum;
    private View viewWordsNum;

    private TextView tvStatisticsWorkNum;
    private TextView tvStatisticsWorkRank;
    private TextView tvStatisticsLikeNum;
    private TextView tvStatisticsLikeRank;
    private TextView tvStatisticsCommentNum;
    private TextView tvStatisticsCommentRank;
    private TextView tvStatisticsBrowserNum;
    private TextView tvStatisticsBrowserRank;
    private TextView tvStatisticsFansNum;
    private TextView tvStatisticsFansRank;
    private TextView tvStatisticsWordsNum;
    private TextView tvStatisticsWordsRank;

    private int type;
    private RequestQueue mQueue;
    private ImageLoader imageLoader;
    private String URL_ACTION = IllustApi.getStats();
    private String id;
    private Statistics statistics;
    private ProgressbarHelper mProgressbarHelper;
    private String sharePath;
    private View pbShare;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.statistics_layout);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        imageLoader = ImageLoader.getInstance();
        Intent intent = getIntent();
        type = intent.getIntExtra(gotoUtil.INTENT_VALUE_ONE, 0);
        id = intent.getStringExtra(gotoUtil.INTENT_VALUE_TWO);
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        View mActionBarView = findViewById(R.id.base_action_bar);
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        switch (type) {
            case 0:
                mActionbarHelper.setTitle(getString(R.string.statistics_drawer));
                break;
            case 1:
                mActionbarHelper.setTitle(getString(R.string.statistics_writer));
                break;
            case 2:
                mActionbarHelper.setTitle(getString(R.string.statistics_coser));
                break;
        }
    }

    @Override
    protected void initUi() {
        pbShare = findViewById(R.id.pb_share);
        ivStatisticsHeader = (ImageView) findViewById(R.id.civ_statistics_header);
        tvStatisticsName = (TextView) findViewById(R.id.tv_statistics_name);
        tvStatisticsJoindate = (TextView) findViewById(R.id.tv_statistics_joindate);

        viewWorkNum = findViewById(R.id.view_worknum);
        viewLikeNum = findViewById(R.id.view_likenum);
        viewCommentNum = findViewById(R.id.view_commentnum);
        viewBrowserNum = findViewById(R.id.view_browsernum);
        viewFansNum = findViewById(R.id.view_fansnum);
        viewWordsNum = findViewById(R.id.view_wordsnum);

        initCommonStaticBlock(viewWorkNum, R.drawable.work_num, getString(R.string.statistics_work_num));
        initCommonStaticBlock(viewLikeNum, R.drawable.like_num, getString(R.string.statistics_like_num));
        initCommonStaticBlock(viewCommentNum, R.drawable.comment_num, getString(R.string.statistics_comment_num));
        initCommonStaticBlock(viewBrowserNum, R.drawable.viewpage_num, getString(R.string.statistics_browser_num));
        initCommonStaticBlock(viewFansNum, R.drawable.fans_num, getString(R.string.statistics_fans_num));
        initCommonStaticBlock(viewWordsNum, R.drawable.words_num, getString(R.string.statistics_words_num));

        initWorkView();
        initLikeView();
        initCommentView();
        initBrowserView();
        initFansView();
        initWordsView();
    }

    private void initWordsView() {
        tvStatisticsWordsNum = (TextView) viewWordsNum.findViewById(R.id.tv_statistics_block_type_num);
        tvStatisticsWordsRank = (TextView) viewWordsNum.findViewById(R.id.tv_statistics_block_type_percent);
    }

    private void initFansView() {
        tvStatisticsFansNum = (TextView) viewFansNum.findViewById(R.id.tv_statistics_block_type_num);
        tvStatisticsFansRank = (TextView) viewFansNum.findViewById(R.id.tv_statistics_block_type_percent);
    }

    private void initBrowserView() {
        tvStatisticsBrowserNum = (TextView) viewBrowserNum.findViewById(R.id.tv_statistics_block_type_num);
        tvStatisticsBrowserRank = (TextView) viewBrowserNum.findViewById(R.id.tv_statistics_block_type_percent);
    }

    private void initCommentView() {
        tvStatisticsCommentNum = (TextView) viewCommentNum.findViewById(R.id.tv_statistics_block_type_num);
        tvStatisticsCommentRank = (TextView) viewCommentNum.findViewById(R.id.tv_statistics_block_type_percent);
    }

    private void initLikeView() {
        tvStatisticsLikeNum = (TextView) viewLikeNum.findViewById(R.id.tv_statistics_block_type_num);
        tvStatisticsLikeRank = (TextView) viewLikeNum.findViewById(R.id.tv_statistics_block_type_percent);
    }

    private void initWorkView() {
        tvStatisticsWorkNum = (TextView) viewWorkNum.findViewById(R.id.tv_statistics_block_type_num);
        tvStatisticsWorkRank = (TextView) viewWorkNum.findViewById(R.id.tv_statistics_block_type_percent);
    }

    private void initCommonStaticBlock(View viewParent, int statisticsIcon, String statisticsType) {
        ImageView ivStatisticsIcon = (ImageView) viewParent.findViewById(R.id.iv_statistics_block_icon);
        TextView tvStatisticsType = (TextView) viewParent.findViewById(R.id.tv_statistics_block_type);
        ivStatisticsIcon.setImageResource(statisticsIcon);
        tvStatisticsType.setText(statisticsType);
    }


    @Override
    protected void initAction() {
        findViewById(R.id.tv_show_statistics).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        initStatistics();
    }

    private void initShare() {
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        String SHAREE_ACTION = IllustApi.getShareStats();
        switch (type) {
            case 0:
                SHAREE_ACTION = IllustApi.getShareStats();
                paramsList.add(new BcyPair(HttpUtils.DPID, id));
                break;
            case 1:
                SHAREE_ACTION = NovelApi.getShareStats();
                paramsList.add(new BcyPair(HttpUtils.WPID, id));
                break;
            case 2:
                SHAREE_ACTION = CoserApi.getShareStats();
                paramsList.add(new BcyPair(HttpUtils.CPID, id));
                break;
        }
        String url = HttpUtils.BASE_URL + SHAREE_ACTION;
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                pbShare.setVisibility(View.GONE);
                try {
                    JSONObject result = new JSONObject(s);
                    if (StatusCodeUtils.dealStatusCode(s, StatisticsActivity.this)) {
                        sharePath = result.getJSONObject(HttpUtils.UPLOAD_DATA).getString("path");
                        goShare();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                pbShare.setVisibility(View.GONE);
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void initStatistics() {
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        switch (type) {
            case 0:
                URL_ACTION = IllustApi.getStats();
                paramsList.add(new BcyPair(HttpUtils.DPID, id));
                break;
            case 1:
                URL_ACTION = NovelApi.getStats();
                paramsList.add(new BcyPair(HttpUtils.WPID, id));
                break;
            case 2:
                URL_ACTION = CoserApi.getStats();
                paramsList.add(new BcyPair(HttpUtils.CPID, id));
                break;
        }
        String url = HttpUtils.BASE_URL + URL_ACTION;
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject result = new JSONObject(s);
                    if (StatusCodeUtils.dealStatusCode(s, StatisticsActivity.this)) {
                        Gson gson = new Gson();
                        statistics = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA),
                                Statistics.class);
                        processData();
                        mProgressbarHelper.onSuccess();
                    } else {
                        mProgressbarHelper.onFailed();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void processData() {
        processUserData();
        processPostData();
        processDingData();
        processReplyData();
        processViewCountData();
        processFanData();
        processWordCountData();
    }

    private void processWordCountData() {
        StatisticsItem statisticsWord_count = statistics.getWord_count();
        if (null != statisticsWord_count) {
            tvStatisticsWordsNum.setText(statisticsWord_count.getCount());
            tvStatisticsWordsRank.setText(statisticsWord_count.getRank());
            viewWordsNum.setVisibility(View.VISIBLE);
        } else {
            viewWordsNum.setVisibility(View.INVISIBLE);
        }
    }

    private void processFanData() {
        StatisticsItem statisticsFan = statistics.getFan();
        if (null != statisticsFan) {
            tvStatisticsFansNum.setText(statisticsFan.getCount());
            tvStatisticsFansRank.setText(statisticsFan.getRank());
            viewFansNum.setVisibility(View.VISIBLE);
        } else {
            viewFansNum.setVisibility(View.INVISIBLE);
        }
    }

    private void processViewCountData() {
        StatisticsItem statisticsView_count = statistics.getView_count();
        if (null != statisticsView_count) {
            tvStatisticsBrowserNum.setText(statisticsView_count.getCount());
            tvStatisticsBrowserRank.setText(statisticsView_count.getRank());
            viewBrowserNum.setVisibility(View.VISIBLE);
        } else {
            viewBrowserNum.setVisibility(View.INVISIBLE);
        }
    }

    private void processReplyData() {
        StatisticsItem statisticsReply = statistics.getReply();
        if (null != statisticsReply) {
            tvStatisticsCommentNum.setText(statisticsReply.getCount());
            tvStatisticsCommentRank.setText(statisticsReply.getRank());
            viewCommentNum.setVisibility(View.VISIBLE);
        } else {
            viewCommentNum.setVisibility(View.INVISIBLE);
        }
    }

    private void processDingData() {
        StatisticsItem statisticsDing = statistics.getDing();
        if (null != statisticsDing) {
            tvStatisticsLikeNum.setText(statisticsDing.getCount());
            tvStatisticsLikeRank.setText(statisticsDing.getRank());
            viewLikeNum.setVisibility(View.VISIBLE);
        } else {
            viewLikeNum.setVisibility(View.INVISIBLE);
        }
    }

    private void processPostData() {
        StatisticsItem statisticsPost = statistics.getPost();
        if (null != statisticsPost) {
            tvStatisticsWorkNum.setText(statisticsPost.getCount());
            tvStatisticsWorkRank.setText(statisticsPost.getRank());
            viewWorkNum.setVisibility(View.VISIBLE);
        } else {
            viewWorkNum.setVisibility(View.INVISIBLE);
        }
    }

    private void processUserData() {
        User user = statistics.getUser();
        if (null != user) {
            imageLoader.displayImage(user.getAvatar(), ivStatisticsHeader, ImageOptions.options);
            tvStatisticsName.setText(Html.fromHtml(user.getUname()));
            tvStatisticsJoindate.setText(String.format(getString(R.string.join_bcy_date), user.getJoin_days()));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_show_statistics:
                if (TextUtils.isEmpty(sharePath)) {
                    pbShare.setVisibility(View.VISIBLE);
                    initShare();
                } else {
                    goShare();
                }
                break;
        }
    }

    private void goShare() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("content", String.format(getString(R.string.share_statistics), statistics.getUser().getUid()));
        map.put("title", String.format(getString(R.string.share_statis_name), statistics.getUser().getUname()));
        map.put("url", "http://bcy.net/u/" + statistics.getUser().getUid());
        map.put("imagePath", sharePath);
        Intent intent = new Intent();
        intent.setClass(this, ShareActivity.class);
        intent.putExtra("showWarnBtn", false);
        intent.putExtra("showCopyLink", false);
        intent.putExtra("map", map);
        startActivity(intent);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }
}
